#ifndef SQLITE_MANAGER_H
#define SQLITE_MANAGER_H

#include <sqlite3.h>
#include <string>
#include <vector>
#include <map>
#include <memory>

// QSO记录结构体
struct QSORecord {
    std::string id;
    std::string date;
    std::string time;
    std::string callsign;
    std::string band;
    std::string frequency;
    std::string mode;
    std::string rst_sent;
    std::string rst_rcvd;
    std::string exch1;
    std::string exch2;
    std::string myexch1;
    std::string myexch2;
    std::string name;
    std::string qth;
    std::string memo;
    std::string data;
    std::string log_creation_date;
    std::string record_create_time;
    std::string record_modify_time;
};

class SQLiteManager {
public:
    static SQLiteManager& getInstance();
    
    bool connect(const std::string& db_path = "hamlog.db");
    void disconnect();
    
    // QSO操作
    bool insertQSO(const QSORecord& record);
    bool updateQSO(const QSORecord& record);
    bool deleteQSO(const std::string& id);
    bool setDataFieldValue(const std::string& id, const std::string& field, const std::string& value);
    std::vector<QSORecord> getAllQSOs();
    std::vector<QSORecord> getAllQSOs(int page, int pageSize, int& totalCount);
    std::vector<QSORecord> getQSOsByCallsign(const std::string& callsignPrefix);
    std::vector<QSORecord> getQSOsByCallsign(const std::string& callsignPrefix, int page, int pageSize, int& totalCount);
    QSORecord getQSOById(const std::string& id);
    
    // JSON操作
    bool saveJSON(const std::string& key, const std::string& json_data);
    std::string loadJSON(const std::string& key);
    bool deleteJSON(const std::string& key);
    
private:
    SQLiteManager();
    ~SQLiteManager();
    
    SQLiteManager(const SQLiteManager&) = delete;
    SQLiteManager& operator=(const SQLiteManager&) = delete;
    
    bool initializeDatabase();
    std::string escapeString(const std::string& str);
    std::string cleanString(const std::string& str);
    
    sqlite3* db_;
    std::string db_path_;
};

#endif // SQLITE_MANAGER_H